package com.jml.service;


import com.alibaba.fastjson.JSONObject;
import com.jml.config.JmlCloudConfig;
import com.jml.config.ServerConfig;
import com.jml.utils.HttpClientUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;

public class RegisterService {

    private static final Log log = LogFactory.getLog(RegisterService.class);

    @Autowired
    private ServerConfig serverConfig;

    @Autowired
    private JmlCloudConfig jmlCloudConfig;

    @Autowired
    private ServiceRenewal serviceRenewal;

    public void register() {
        Boolean needRenewal = Boolean.TRUE;
        while (true) {
            JSONObject data = requestParameter();
            //获取注册中心的地址，这个是在配置文件配置的。
            String serverAddres = jmlCloudConfig.getServerAddres();
            //服务注册
            JSONObject result = null;
            try {
                result = HttpClientUtils.httpPost(serverAddres + "/register", data);
                log.info("服务注册结果:" + result);
            } catch (Exception e) {
                log.error("注册异常");
                needRenewal = Boolean.FALSE;
            }
            if (result != null && needRenewal) {
                //服务续约
                serviceRenewal.start();
                break;
            }
        }
    }

    public void remove() {
        JSONObject data = requestParameter();
        //获取注册中心的地址，这个是在配置文件配置的。
        String serverAddres = jmlCloudConfig.getServerAddres();
        JSONObject result = HttpClientUtils.httpPost(serverAddres + "/remove/service", data);
        log.info("服务停止-剔除服务参数:" + data);
        log.info("服务停止-剔除服务serverAddres:" + serverAddres);
        log.info("服务停止-剔除服务:" + result);
    }

    public JSONObject requestParameter() {
        return requestParameter(null);
    }

    public JSONObject requestParameter(Long renewalDuration) {
        //获取本项目IP+端口
        String serviceUrl = serverConfig.getAppHostAndPort();
        //获取服务名称
        String serviceName = jmlCloudConfig.getServiceName();
        JSONObject data = new JSONObject();
        data.put("serviceName", serviceName);
        data.put("serviceAddres", serviceUrl);
        if (renewalDuration != null) {
            data.put("renewalDuration", renewalDuration);
        }
        return data;
    }

    /**
     * 客户端续约
     */
    public void renewal() {
        JSONObject data = requestParameter(5000L);
        //获取注册中心的地址，这个是在配置文件配置的。
        String serverAddres = jmlCloudConfig.getServerAddres();
        JSONObject result = HttpClientUtils.httpPost(serverAddres + "/renewal", data);
        log.info("服务续约：" + result);
    }


}
